package com.ef.service.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.ef.constant.StatusType;
import com.ef.dao.ClassUnitDao;
import com.ef.dao.CourseDao;
import com.ef.domain.ClassUnit;
import com.ef.domain.Course;
import com.ef.service.CourseService;
import com.ef.util.CustomExample;
import com.ef.util.PaginationSupport;

public class CourseServiceImpl extends BaseServiceImpl implements CourseService {

	private CourseDao courseDao;
	private ClassUnitDao classUnitDao;

	public void delete(Course entity) {
		entity.setStatus(StatusType.INVALID);
		courseDao.update(entity);

	}

	public PaginationSupport<Course> findByExample(
			CustomExample<Course> example, int startIndex, int pageSize) {

		return courseDao.findPageByExample(example, startIndex, pageSize);
	}

	public Course findById(Long id) {

		return courseDao.findById(id);
	}

	public void saveOrUpdate(Course entity) {

		courseDao.saveOrUpdate(entity);
	}

	public List<Course> findALL() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Course.class);
		criteria.add(Restrictions.eq("status", StatusType.VALID));
		return courseDao.findAllByCriteria(criteria);
	}

	public void deleteByCourse(Course course) {
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ClassUnit.class);
		detachedCriteria.add(Restrictions.eq("course", course));
		List<ClassUnit> list = classUnitDao.findAllByCriteria(detachedCriteria);
		for(ClassUnit cu:list ){
			//cu.setStatus(StatusType.INVALID);
			classUnitDao.saveOrUpdate(cu);
		}
	}
	
	public List<ClassUnit> findByCourse(Course course){
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ClassUnit.class);
		detachedCriteria.add(Restrictions.eq("course", course));
		detachedCriteria.add(Restrictions.eq("status", StatusType.VALID));
		List<ClassUnit> list = classUnitDao.findAllByCriteria(detachedCriteria);
		return  list;
	}

	public void saveSelectedClass(List<ClassUnit> classUnits) {
		
		for(ClassUnit cl :classUnits){
			classUnitDao.save(cl);
		}
	}

	public CourseDao getCourseDao() {
		return courseDao;
	}

	public void setCourseDao(CourseDao courseDao) {
		this.courseDao = courseDao;
	}

	public ClassUnitDao getClassUnitDao() {
		return classUnitDao;
	}

	public void setClassUnitDao(ClassUnitDao classUnitDao) {
		this.classUnitDao = classUnitDao;
	}

}
